<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');


if (! defined('ORDER_COMMIT'))                                  define('ORDER_COMMIT', (1 << 0));
if (! defined('ORDER_DISCOUNT'))                                define('ORDER_DISCOUNT', (1 << 1));
if (! defined('ORDER_PAID'))                                    define('ORDER_PAID', (1 << 2));
if (! defined('ORDER_CONFIRM'))                                 define('ORDER_CONFIRM', (1 << 6));
if (! defined('ORDER_SHIPMENT'))                                define('ORDER_SHIPMENT', (1 << 3));
if (! defined('ORDER_DELIVER'))                                 define('ORDER_DELIVER', (1 << 4));
if (! defined('ORDER_REFUND'))                                  define('ORDER_REFUND', (1 << 5));
if (! defined('ORDER_CANCEL'))                                  define('ORDER_CANCEL', (1 << 30));

if (! defined('AUDIT_NONE'))                                    define('AUDIT_NONE', 0);
if (! defined('AUDIT_APPLY'))                                   define('AUDIT_APPLY', 1);
if (! defined('AUDIT_YES'))                                     define('AUDIT_YES', 2);
if (! defined('AUDIT_NO'))                                      define('AUDIT_NO', 3);

if (! defined('INVOICE_NONE'))                                  define('INVOICE_NONE', 0);
if (! defined('INVOICE_REGULAR'))                               define('INVOICE_REGULAR', 1);
if (! defined('INVOICE_VAT'))                                   define('INVOICE_VAT', 2);

if (! defined('GOODS_DISCUSS_CANT'))                            define('GOODS_DISCUSS_CANT', 1);
if (! defined('GOODS_DISCUSS_YES'))                             define('GOODS_DISCUSS_YES', 2);
if (! defined('GOODS_DISCUSS_NO'))                              define('GOODS_DISCUSS_NO', 3);

// 店主权限列表
if (! defined('SHOP_PRIVILEGE_SHOP'))                           define('SHOP_PRIVILEGE_SHOP', (1 << 0));
if (! defined('SHOP_PRIVILEGE_GOODS'))                          define('SHOP_PRIVILEGE_GOODS', (1 << 1));
if (! defined('SHOP_PRIVILEGE_ORDER'))                          define('SHOP_PRIVILEGE_ORDER', (1 << 2));
if (! defined('SHOP_PRIVILEGE_CONSUME'))                        define('SHOP_PRIVILEGE_CONSUME', (1 << 3));
if (! defined('SHOP_PRIVILEGE_CONSULT'))                        define('SHOP_PRIVILEGE_CONSULT', (1 << 4));
if (! defined('SHOP_PRIVILEGE_MESSAGE'))                        define('SHOP_PRIVILEGE_MESSAGE', (1 << 5));
if (! defined('SHOP_PRIVILEGE_ACCOUNT'))                        define('SHOP_PRIVILEGE_ACCOUNT', (1 << 6));

// 进销存权限列表
if (! defined('INVOICING_PRIVILEGE_ORDER_PROC'))                define('INVOICING_PRIVILEGE_ORDER_PROC', (1 << 0));
if (! defined('INVOICING_PRIVILEGE_ORDER_MANAGE'))              define('INVOICING_PRIVILEGE_ORDER_MANAGE', (1 << 1));
if (! defined('INVOICING_PRIVILEGE_ORDER_CANCEL'))              define('INVOICING_PRIVILEGE_ORDER_CANCEL', (1 << 2));
if (! defined('INVOICING_PRIVILEGE_ORDER_CUSTOMER'))            define('INVOICING_PRIVILEGE_ORDER_CUSTOMER', (1 << 3));
if (! defined('INVOICING_PRIVILEGE_WARE_HOUSE'))                define('INVOICING_PRIVILEGE_WARE_HOUSE', (1 << 4));
if (! defined('INVOICING_PRIVILEGE_WARE_HOUSE_GOODS_ADD'))      define('INVOICING_PRIVILEGE_WARE_HOUSE_GOODS_ADD', (1 << 5));
if (! defined('INVOICING_PRIVILEGE_WARE_HOUSE_CHECK'))          define('INVOICING_PRIVILEGE_WARE_HOUSE_CHECK', (1 << 6));
if (! defined('INVOICING_PRIVILEGE_WARE_HOUSE_GOODS_VIEW'))     define('INVOICING_PRIVILEGE_WARE_HOUSE_GOODS_VIEW', (1 << 7));
if (! defined('INVOICING_PRIVILEGE_WARE_HOUSE_BALANCE'))        define('INVOICING_PRIVILEGE_WARE_HOUSE_BALANCE', (1 << 8));
if (! defined('INVOICING_PRIVILEGE_SETTLE_ACCOUNT'))            define('INVOICING_PRIVILEGE_SETTLE_ACCOUNT', (1 << 9));
if (! defined('INVOICING_PRIVILEGE_SETTLE_OTHER'))              define('INVOICING_PRIVILEGE_SETTLE_OTHER', (1 << 10));
if (! defined('INVOICING_PRIVILEGE_SETTLE_MEMBER'))             define('INVOICING_PRIVILEGE_SETTLE_MEMBER', (1 << 11));
if (! defined('INVOICING_PRIVILEGE_SETTLE_HISTORY_MODIFY'))     define('INVOICING_PRIVILEGE_SETTLE_HISTORY_MODIFY', (1 << 12));
if (! defined('INVOICING_PRIVILEGE_SETTLE_CANCEL'))             define('INVOICING_PRIVILEGE_SETTLE_CANCEL', (1 << 13));
if (! defined('INVOICING_PRIVILEGE_SALE_SINGLE_DISCOUNT'))      define('INVOICING_PRIVILEGE_SALE_SINGLE_DISCOUNT', (1 << 14));
if (! defined('INVOICING_PRIVILEGE_SALE_SINGLE_PRESENT'))       define('INVOICING_PRIVILEGE_SALE_SINGLE_PRESENT', (1 << 15));
if (! defined('INVOICING_PRIVILEGE_SALE_DISCOUNT'))             define('INVOICING_PRIVILEGE_SALE_DISCOUNT', (1 << 16));
if (! defined('INVOICING_PRIVILEGE_SALE_WHOLE_PRESENT'))        define('INVOICING_PRIVILEGE_SALE_WHOLE_PRESENT', (1 << 17));
if (! defined('INVOICING_PRIVILEGE_SALE_RETURN'))               define('INVOICING_PRIVILEGE_SALE_RETURN', (1 << 18));
if (! defined('INVOICING_PRIVILEGE_FINANCE_REPORT'))            define('INVOICING_PRIVILEGE_FINANCE_REPORT', (1 << 19));
if (! defined('INVOICING_PRIVILEGE_FINANCE_CERTIFICATE'))       define('INVOICING_PRIVILEGE_FINANCE_CERTIFICATE', (1 << 20));
if (! defined('INVOICING_PRIVILEGE_FINANCE_AUDIT'))             define('INVOICING_PRIVILEGE_FINANCE_AUDIT', (1 << 21));
if (! defined('INVOICING_PRIVILEGE_FINANCE_BUSINESS_VIEW'))     define('INVOICING_PRIVILEGE_FINANCE_BUSINESS_VIEW', (1 << 22));
if (! defined('INVOICING_PRIVILEGE_FINANCE_HISTORY_AUDIT'))     define('INVOICING_PRIVILEGE_FINANCE_HISTORY_AUDIT', (1 << 23));
if (! defined('INVOICING_PRIVILEGE_SYSTEM_INFO_MANAGE'))        define('INVOICING_PRIVILEGE_SYSTEM_INFO_MANAGE', (1 << 24));
if (! defined('INVOICING_PRIVILEGE_SYSTEM_GOODS'))              define('INVOICING_PRIVILEGE_SYSTEM_GOODS', (1 << 25));
if (! defined('INVOICING_PRIVILEGE_SYSTEM_STAFF'))              define('INVOICING_PRIVILEGE_SYSTEM_STAFF', (1 << 26));

// OA 权限列表
if (! defined('OA_PRIVILEGE_PERMIT'))					        define('OA_PRIVILEGE_PERMIT', (1 << 0));
if (! defined('OA_PRIVILEGE_FIXED_ASSETS'))				        define('OA_PRIVILEGE_FIXED_ASSETS', (1 << 1));
if (! defined('OA_PRIVILEGE_HR'))					            define('OA_PRIVILEGE_HR', (1 << 2));
if (! defined('OA_PRIVILEGE_NOTICE'))					        define('OA_PRIVILEGE_NOTICE', (1 << 3));
if (! defined('OA_PRIVILEGE_RULE'))						        define('OA_PRIVILEGE_RULE', (1 << 4));
if (! defined('OA_PRIVILEGE_TASK_ASSIGN'))				        define('OA_PRIVILEGE_TASK_ASSIGN', (1 << 5));
if (! defined('OA_PRIVILEGE_FINANCE'))				            define('OA_PRIVILEGE_FINANCE', (1 << 6));

// CRM 权限列表
if (! defined('CRM_PRIVILEGE_PERMIT'))					        define('CRM_PRIVILEGE_PERMIT', (1 << 0));
if (! defined('CRM_PRIVILEGE_STAT'))					        define('CRM_PRIVILEGE_STAT', (1 << 1));

// ERP 权限列表
if (! defined('ERP_PRIVILEGE_PERMIT'))					        define('ERP_PRIVILEGE_PERMIT', (1 << 0));
if (! defined('ERP_PRIVILEGE_STAFF_SALES'))                     define('ERP_PRIVILEGE_STAFF_SALES', (1 << 1));
if (! defined('ERP_PRIVILEGE_MONTH_PROFIT'))                    define('ERP_PRIVILEGE_MONTH_PROFIT', (1 << 2));
if (! defined('ERP_PRIVILEGE_DAY_PROFIT'))                      define('ERP_PRIVILEGE_DAY_PROFIT', (1 << 3));
if (! defined('ERP_PRIVILEGE_BOSS'))					        define('ERP_PRIVILEGE_BOSS', (1 << 4));

// OA 流程控制
if (! defined('OA_FLOW_ROLE_FINANCE'))                          define('OA_FLOW_ROLE_FINANCE', (1 << 0));
if (! defined('OA_FLOW_ROLE_ASSET'))                            define('OA_FLOW_ROLE_ASSET', (1 << 1));
if (! defined('OA_FLOW_ROLE_DIMISSION'))                        define('OA_FLOW_ROLE_DIMISSION', (1 << 2));
if (! defined('OA_FLOW_ROLE_OVERTIME'))                         define('OA_FLOW_ROLE_OVERTIME', (1 << 3));
if (! defined('OA_FLOW_ROLE_LEAVE'))                            define('OA_FLOW_ROLE_LEAVE', (1 << 4));

// OA 固定资产
if (! defined('OA_FIXEDASSETS_NOTUSE'))                         define('OA_FIXEDASSETS_NOTUSE', (1 << 0));
if (! defined('OA_FIXEDASSETS_CONSUMING'))                      define('OA_FIXEDASSETS_CONSUMING', (1 << 1));
if (! defined('OA_FIXEDASSETS_CONSUMED'))                       define('OA_FIXEDASSETS_CONSUMED', (1 << 2));
if (! defined('OA_FIXEDASSETS_REPAIRED'))                       define('OA_FIXEDASSETS_REPAIRED', (1 << 3));
if (! defined('OA_FIXEDASSETS_SCRAPPED'))                       define('OA_FIXEDASSETS_SCRAPPED', (1 << 4));


if ( ! function_exists('is_valid_role'))
{
    function is_valid_role($role, $guest_register = false)
    {
        if ($guest_register)
            return in_array($role, array('customer', 'shopkeeper'));

        return in_array($role, array('admin', 'agent', 'customer', 'shopkeeper'));
    }
}

if ( ! function_exists('role_name'))
{
    function role_name($role)
    {
        $roles = array(
                    'admin' => '管理员',
                    'agent' => '客服',
                    'customer' => '买家',
                    'shopkeeper' => '商家'
                );

        if (isset($roles[$role]))
            return $roles[$role];

        return '';
    }
}

if ( ! function_exists('oa_flow_role_name'))
{
    function oa_flow_role_name($role)
    {
        $role = intval($role);

        $roles = array(
                    OA_FLOW_ROLE_FINANCE => '财务审核',
                    OA_FLOW_ROLE_ASSET => '资产审核',
                    OA_FLOW_ROLE_DIMISSION => '离职审核',
                    OA_FLOW_ROLE_OVERTIME => '加班审核',
                    OA_FLOW_ROLE_LEAVE => '请假审核',
                );

        if (isset($roles[$role]))
            return $roles[$role];

        return '';
    }
}

if ( ! function_exists('oa_fixed_assets_status'))
{
    function oa_fixed_assets_status($statu)
    {
        $statu = intval($statu);

        $status = array(
                    OA_FIXEDASSETS_NOTUSE => '不可领用',
                    OA_FIXEDASSETS_CONSUMING => '可领用',
                    OA_FIXEDASSETS_CONSUMED => '已领用',
                    OA_FIXEDASSETS_REPAIRED => '已报修',
                    OA_FIXEDASSETS_SCRAPPED => '已报废',
                );

        $status_str = array();
        foreach ($status as $k => $v) {
            if ($k == OA_FIXEDASSETS_CONSUMING and $statu & OA_FIXEDASSETS_CONSUMING and $statu != OA_FIXEDASSETS_CONSUMING)
                continue;
            
            if ($k & $statu)
                $status_str[] = $v;
        }

        return join('、', $status_str);
    }
}

if ( ! function_exists('is_user'))
{
    function is_user($controller)
    {
        return $controller->session->userdata('authed');
    }
}

if ( ! function_exists('is_admin'))
{
    function is_admin($controller)
    {
        return $controller->session->userdata('role') == 'admin';
    }
}

if ( ! function_exists('is_agent'))
{
    function is_agent($controller)
    {
        return $controller->session->userdata('role') == 'agent';
    }
}

if ( ! function_exists('is_customer'))
{
    function is_customer($controller)
    {
        return $controller->session->userdata('role') == 'customer';
    }
}

if ( ! function_exists('bit_set'))
{
    function bit_set($val, $mask)
    {
        return ($val & $mask) === $mask;
    }
}

if ( ! function_exists('is_shopkeeper'))
{
    function is_shopkeeper($controller, $module = null, $which_privilege = false, $permit_null = true)
    {
        if ($controller->session->userdata('role') !== 'shopkeeper')
            return false;
    
        if ($module === null)
            return true;

        if ($which_privilege === false)
            return true;

        $privilege = $controller->session->userdata($module);
        if ($permit_null and $privilege === false)
            return true;

        return ((intval($privilege) & $which_privilege) === $which_privilege) ? true : false;
    }
}

if ( ! function_exists('hint_message'))
{
    function hint_message($success = true, $message = '', $args = array())
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); 
        header("Cache-Control: no-cache, must-revalidate"); 
        header("Pramga: no-cache"); 
        header('Content-Type: application/json');

        $result = array();

        $result['status'] = $success ? 'success': 'error';
        $result['message'] = $message;

        if ($args) {
            foreach ($args as $k => $v) {
                $result[$k] = $v;
            }
        }

        echo json_encode($result);
    }
}

if ( ! function_exists('table_sort'))
{
    function table_sort($sort, $maps = array())
    {
        if(! $sort or ! is_array($sort))
            return '';

        $sql = '';

        foreach ($sort as $k => $v) {
            $field = $v['field'];
            $direction = $v['direction'];

            if (isset($maps[$field]))
                $field = $maps[$field];

            $direction = strtolower($direction) == 'desc' ? 'DESC' : 'ASC';

            if ($sql === '')
                $sql = "ORDER BY $field $direction";
            else
                $sql .= ", $field $direction";
        }

        return $sql;
    }
}

if ( ! function_exists('table_search'))
{
    function table_search($controller, $maps = array())
    {
        $search = $controller->input->get_post('search');
        $search_logic = $controller->input->get_post('searchLogic');

        $sql = '';

        if (! $search or ! is_array($search) or ! in_array($search_logic, array('AND', 'OR')))
            return $sql;

        foreach ($search as $k => $v) {
            if ($v === '')
                continue;

            $name = $v['field'];
            $value = $v['value'];

            if (is_array($value)) { // should be list
                if (isset($value['id']))
                    $value = $value['id'];
                else
                    continue;
            }

            if ($value == '')
                continue;

            if (isset($v['operator']))
                $operator = $v['operator'];
            else
                $operator = 'contains';

            if (isset($maps[$name]))
                $name = $maps[$name];

            if ($sql !== '')
                $sql .= " $search_logic ";

            if ($operator == 'contains') {
                $value = $controller->db->escape_like_str($value);
                $sql .= "$name LIKE '%" . $value . "%'";
            } else if (in_array($operator, array('begins', 'begins with'))) {
                $value = $controller->db->escape_like_str($value);
                $sql .= "$name LIKE '" . $value . "%'";
            } else if (in_array($operator, array('ends', 'ends with'))) {
                $value = $controller->db->escape_like_str($value);
                $sql .= "$name LIKE '%" . $value . "'";
            } else if ($operator == 'ends with') {
                $value = $controller->db->escape_str($value);
                $sql .= "$name = '%" . $value . "'";
            }
        }

        return $sql;
    }
}

if ( ! function_exists('table_args'))
{
    function table_args($controller, $maps = array())
    {
        $start = trim($controller->input->get_post('offset'));
        $count = trim($controller->input->get_post('limit'));
        $sort = $controller->input->get_post('sort');

        $args = array();

        try {
            $start = intval($start);
        } catch (Exception $e) {
            $start = 0;
        }

        try {
            $count = intval($count);
            if ($count <= 0)
                throw new Exception('a');
        } catch (Exception $e) {
            $count = 25;
        }

        $args = array(
            'start' => $start,
            'count' => $count,
            'sort' => table_sort($sort, $maps),
            'filter' => table_search($controller, $maps)
        );

        return $args;
    }
}

if ( ! function_exists('table_data'))
{
    function table_data($total = 0, $rows = array())
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); 
        header("Cache-Control: no-cache, must-revalidate"); 
        header("Pramga: no-cache"); 
        header('Content-Type: application/json');

        echo json_encode(array('status' => 'success', 'total' => $total, 'records' => $rows));
    }
}

if ( ! function_exists('datatable_args'))
{
    function datatable_args($controller, $maps = array())
    {
        $start = trim($controller->input->get_post('iDisplayStart'));
        $count = trim($controller->input->get_post('iDisplayLength'));
        $sort = $controller->input->get_post('sort');

        $args = array();

        try {
            $start = intval($start);
        } catch (Exception $e) {
            $start = 0;
        }

        try {
            $count = intval($count);
            if ($count <= 0)
                $count = 10000000;
        } catch (Exception $e) {
            $count = 25;
        }

        $args = array(
            'start' => $start,
            'count' => $count,
            'sort' => table_sort($sort, $maps),
            'filter' => table_search($controller, $maps)
        );

        return $args;
    }
}

if ( ! function_exists('datatable_data'))
{
    function datatable_data($total = 0, $rows = array())
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); 
        header("Cache-Control: no-cache, must-revalidate"); 
        header("Pramga: no-cache"); 
        header('Content-Type: application/json');

        echo json_encode(array('iTotalRecords' => $total, 'iTotalDisplayRecords' => $total, 'aaData' => $rows));
    }
}

if ( ! function_exists('get_shop_status_str'))
{
    function get_shop_status_str($status)
    {
        $a = array(
            'online' => '<font color="green">线上</font>',
            'offline' => '<font color="orange">线下</font>',
            'banned' => '<font color="red">封停</font>'
        );

        if (isset($a[$status]))
            return $a[$status];

        return '';
    }
}

if ( ! function_exists('get_shop_audit_str'))
{
    function get_shop_audit_str($audit)
    {
        $audit = '' . $audit;

        $a = array(
            AUDIT_NONE => '未申请',
            AUDIT_APPLY => '<font color="#F5D0A9">审核中</font>',
            AUDIT_YES => '<font color="green">已通过</font>',
            AUDIT_NO => '<font color="red">未通过</font>'
        );

        if (isset($a[$audit]))
            return $a[$audit];

        return '';
    }
}

if ( ! function_exists('get_oa_audit_str'))
{
    function get_oa_audit_str($audit)
    {
        $audit = '' . $audit;

        $a = array(
            AUDIT_NONE => '未申请',
            AUDIT_APPLY => '<font color="#F5D0A9">申请中</font>',
            AUDIT_YES => '<font color="green">已批准</font>',
            AUDIT_NO => '<font color="red">未批准</font>'
        );

        if (isset($a[$audit]))
            return $a[$audit];

        return '';
    }
}

if ( ! function_exists('get_shop_permit_str'))
{
    function get_shop_permit_str($permit)
    {
        $permit = '' . $permit;

        $a = array(
            AUDIT_APPLY => '<font color="#F5D0A9">申请中</font>',
            AUDIT_YES => '<font color="green">已允许</font>',
            AUDIT_NO => '<font color="red">已拒绝</font>'
        );

        if (isset($a[$permit]))
            return $a[$permit];

        return '';
    }
}

if ( ! function_exists('get_yes_str'))
{
    function get_yes_str($yes)
    {
        if (trim($yes))
            return '<font color="green">是</font>';

        return '<font color="red">否</font>';
    }
}

// ...

if ( ! function_exists('upload_file_name'))
{
    function upload_file_name($file, $path, $check_suffix = '', $new_suffix = '')
    {
        $name = $file['name'];
        $suffix = strrchr($name, '.');
        if (! $suffix)
            return '';

        if ($check_suffix !== '') {
            $matched = false;
            if (gettype($check_suffix) == 'array') {
                foreach ($check_suffix as $v) {
                    if ($v === $suffix) {
                        $matched = true;
                        break;
                    }
                }
            } else {
                if ($suffix === $check_suffix)
                    $matched = true;
            }

            if (! $matched)
                return '';
        }

        if ($new_suffix !== '')
            $suffix = '.' . $new_suffix;

        $file_name = $path . '/' . uniqid() . strtolower($suffix);

        return $file_name;
    }
}

if ( ! function_exists('image_compress'))
{
    function image_compress($file, $mime, $args = array())
    {
        $tmp_file = '';

        if (! isset($args['transparent']))
            $args['transparent'] = true;

        try {
            list($width, $height) = getimagesize($file);

            if (isset($args['max_width']) or isset($args['max_height'])) {
                $new_width = $width;
                $new_height = $height;

                if (isset($args['max_width']) and $width > $args['max_width']) {
                    $new_width = $args['max_width'];
                    $new_height = intval($height * $new_width / $width);
                }

                if (isset($args['max_height']) and $height > $args['max_height']) {
                    $new_height = $args['max_height'];
                    $new_width = intval($width * $new_height / $height);
                }
            } else if (isset($args['width']) and isset($args['height'])) {
                $new_width = $args['width'];
                $new_height = $args['height'];
            } else if (isset($args['height'])) {
                $new_height = $args['height'];
                $new_width = intval($width * $new_height / $height);
            } else if (isset($args['width'])) {
                $new_width = $args['width'];
                $new_height = intval($height * $new_width / $width);
            } else {
                $new_width = $width;
                $new_height = $height;
            }

            switch ($mime) {
                case 'image/png':
                case 'image/x-png':
                    $image = imagecreatefrompng($file);
                    break;

                case 'image/gif':
                    $image = imagecreatefromgif($file);
                    break;

                case 'image/jpeg':
                    $image = imagecreatefromjpeg($file);
                    break;
    
                default:
                    throw new Exception('a');
            }

            $new_image = imagecreatetruecolor($new_width, $new_height);
            imagesavealpha($image, true);

            if ($args['transparent']) {
                if ($args['type'] == 'png') {
                    imagealphablending($new_image, false);
                    imagesavealpha($new_image, true);
                } else if ($args['type'] == 'gif') {
                    $color = imagecolorallocate($new_image, 255, 255, 255);
                    imagecolortransparent($new_image, $color);
                    imagefill($new_image, 0, 0, $color);
                }
            }

            imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

            if ($args['type'] == 'png') {
                $tmp_file = tempnam(sys_get_temp_dir(), 'imr_');
                if (! $tmp_file)
                    throw new Exception('b');

                imagepng($new_image, $tmp_file);
            } else if($args['type'] == 'gif') {
                $tmp_file = tempnam(sys_get_temp_dir(), 'imr_');
                if (! $tmp_file)
                    throw new Exception('b');

                imagegif($new_image, $tmp_file);
            } else {
                $tmp_file = tempnam(sys_get_temp_dir(), 'imr_');
                if (! $tmp_file)
                    throw new Exception('b');

                imagejpeg($new_image, $tmp_file);//图片质量默认75
            }

            imagedestroy($new_image);

            file_put_contents($file, file_get_contents($tmp_file));
        } catch (Exception $e) {
            @unlink($file);
            $file = '';
        }

        if ($tmp_file)
            unlink($tmp_file);

        return $file;
    }
}

if ( ! function_exists('inner_send_email'))
{
    function inner_send_email($args)
    {
        try {
            $url = 'http://127.0.0.1:7000/send_email';

            $post_data = array(
                'email' => json_encode($args)
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);

            $ret = json_decode($output, true);

            if (isset($ret['status']) and $ret['status'] == 'success')
                return true;
            
        } catch (Exception $e) {
        }

        return false;
    }
}

if ( ! function_exists('send_email'))
{
    function send_email($controller, $to_id, $subject, $body, $is_html = false)
    {
        $controller->load->helper('email');

        if (valid_email($to_id)) {
            $to_email = $to_id;
        } else {
            $controller->load->model('User_settings_model');
            if (! $controller->User_settings_model->get_email_notification($to_id))
                return;

            $controller->load->model('Userinfo_model');
            $to_info = $controller->Userinfo_model->get_info($to_id);
            if (! $to_info or ! valid_email($to_info['Email']))
                return;

            $to_email = $to_info['Email'];
        }

        $controller->load->model('Smtp_model');
        $smtp_info = $controller->Smtp_model->get_info();
        if (! $smtp_info or $smtp_info['IsEnabled'] !== '1')
            return;

        $args = array(
            'host' => $smtp_info['Host'],
            'is_auth' => $smtp_info['IsAuth'],
            'secure' => $smtp_info['Secure'],
            'username' => $smtp_info['Username'],
            'password' => $smtp_info['Password'],
            'from_name' => get_platform_name($controller),
            'from' => $smtp_info['FromAddress'],
            'to' => $to_email,
            'subject' => $subject,
            'body' => $body,
            'is_html' => $is_html
        );

        if (trim($smtp_info['Port']) !== '')
            $args['port'] = $smtp_info['Port'];

        return inner_send_email($args);

        /*
        require_once('application/third_party/PHPMailer/PHPMailerAutoload.php');
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Charset = 'UTF-8';
        $mail->Encoding = 'base64';
        $mail->Host = $smtp_info['Host'];
        if (trim($smtp_info['Port']) !== '')
            $mail->Port = $smtp_info['Port'];
        $mail->SMTPAuth = trim($smtp_info['IsAuth']) === '1' ? true : false;
        if (trim($smtp_info['Secure']) !== '')
            $mail->SMTPSecure = $smtp_info['Secure'];
        $mail->Username = $smtp_info['Username'];
        $mail->Password = $smtp_info['Password'];
        $mail->FromName = get_platform_name($controller);
        $mail->From = $smtp_info['FromAddress'];
        $mail->AddAddress($to_email);
        $mail->Subject = $subject;

        $mail->Body = $body;

        if ($is_html)
            $mail->isHTML(true);
        
        if (! $mail->Send()) {
            error_log("send mail failed: " . $mail->ErrorInfo);
            return false;
        }

        return true;
        */
    }
}

if ( ! function_exists('send_order_message'))
{
    function send_order_message($controller, $order_id, $to_id, $to_name, $title, $body)
    {
        $controller->load->model('Messages_model');
        if (! $controller->Messages_model->add_order_message($order_id, $to_id, $to_name, $title, $body))
            return false;

        return true;
    }
}

if ( ! function_exists('get_disk_info'))
{
    function get_disk_info()
    {
        $disk_info = `df -k 2>/dev/null`;
        if (trim($disk_info) == null)
            return null;

        $pars = array_filter(explode("\n", $disk_info));

        $total = 0;
        $free = 0;

        foreach ($pars as $par) {
            if ($par{0} != '/')
                continue;

            $_tmp = array_values(array_filter(explode(' ', $par)));
            reset($_tmp);

            $total += intval($_tmp[1]) * 1000;
            $free += intval($_tmp[3]) * 1000;
        }

        if ($total === 0)
            return null;

        return array($total, $free, ($total - $free) / $total);
    }
}

if ( ! function_exists('get_mem_info'))
{
    function get_mem_info()
    {
        $mem_info = `cat /proc/meminfo 2>/dev/null`;
        if (trim($mem_info) == null)
            return null;

        $pars = array_filter(explode("\n", $mem_info));

        $total = 0;
        $free = 0;

        foreach ($pars as $par) {
            $_tmp = array_values(array_filter(explode(' ', $par)));
            reset($_tmp);

            if ($_tmp[0] == 'MemTotal:')
                $total = intval($_tmp[1]) * 1024;
            else if ($_tmp[0] == 'MemFree:')
                $free = intval($_tmp[1]) * 1024;
        }

        if ($total === 0)
            return null;

        return array($total, $free, ($total - $free) / $total);
    }
}

if ( ! function_exists('get_cpu_info'))
{
    function get_cpu_info()
    {
        $cpu_info = `mpstat 2>/dev/null`;
        if (trim($cpu_info) == null)
            return null;

        $pars = array_filter(explode("\n", $cpu_info));

        $num = 0;
        $user = 0;
        $sys = 0;

        foreach ($pars as $par) {
            preg_match('/([0-9]+) CPU/', $par, $cpus);
            if ($cpus and count($cpus) == 2) {
                $num = intval($cpus[1]);
            } else {
                $_tmp = array_values(array_filter(explode(' ', $par)));
                reset($_tmp);

                if (count($_tmp) < 6)
                    continue;

                if ($_tmp[1] == 'all') {
                    $user = floatval($_tmp[2]);
                    $sys = floatval($_tmp[4]);
                }
            }
        }

        if ($num == 0)
            return null;

        return array($num, $user + $sys);
    }
}

